from datetime import datetime
from typing import Optional

from pydantic import Field

from app.models.TSModel import TSModel
from app.utils import get_current_time


class DeviceInfo(TSModel):

    @staticmethod
    def generate_rowkey(device_number: str) -> str:
        return device_number[::-1]

    def get_row_key(self) -> str:
        return self.generate_rowkey(self.number)

    __INSTANCE_NAME__: bytes = "flow_guardian".encode('utf-8')
    __TABLE_NAME__: bytes = "device_info".encode('utf-8')
    number: str
    phone_number: str
    business_type: str
    group: str
    remark: str
    status: str
    model: str
    carriers: str
    province: str
    url: str
    platform: Optional[str] = 'onethingcloud'
    user_id: str
    access_key: str
    access_key_expires: str
    refresh_key: str
    refresh_key_expires: str
    last_datetime: Optional[str] = Field(default_factory=get_current_time)

    @classmethod
    def from_data(cls, external_data):
        field_mapping = {
            'number': 'sn',
            'phone_number': 'phone_number',
            'business_type': 'bizType',
            'group': 'deviceGroup',
            'remark': 'deviceRemark',
            'status': 'deviceStatus',
            'model': 'deviceType',
            'carriers': 'isp',
            'province': 'province',
            'url': 'url',
            'user_id': 'user_id',
            'access_key': 'access_key',
            'access_key_expires': 'access_key_expires',
            'refresh_key': 'refresh_key',
            'refresh_key_expires': 'refresh_key_expires'
        }
        device_parameter = {name: str(external_data[value]) for name, value in field_mapping.items()}
        return cls(**device_parameter)
